<?php

namespace app\logic\common;

class L_secretIdKey
{

    private $url = "https://api.ltcms.com";
    private $storePublicKey = "/api/secret/storePublicKey";
    private $storeIdKey = "/api/secret/storeIdKey";
    private $publicKey = ""; //公钥
    public $secretId = ""; //安全id
    public $secretKey = ""; //安全key

    public $err = "";


    function __construct($secretId = null, $secretKey = null)
    {
        if ($secretId) {
            $this->secretId = $secretId;
        }
        if ($secretKey) {
            $this->secretKey = $secretKey;
        }
/*        if (env()->get("APP_debug", "") == 1) {
            $this->url = "http://www.cms3.com";
        }*/
    }


    //获取rsa公钥
    public function getPublicKey(): bool
    {
        //$ret = http_get($this->url . $this->storePublicKey); //修改host不生效,无法测试
        $ret = file_get_contents($this->url . $this->storePublicKey);
        //{"success":true,"code":0,"codeMsg":"success","data":"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCq8rVAwXpyhnwOHo8ZY7x04mtJ\nzDPNhRjdDwJWWlKMm5nud+r\/v0rZtgiTmnvHQ+aUpqT2I+25QuJP8sWn19yVt2lU\ng+nlQY1Ac1vaT67IyLdlz1Fo5J3lGHe5dTCOd3fmp\/AFTbkA1BMPTDce5RzJCCM6\nnTFtM3SZXGcPIjPEpwIDAQAB\n-----END PUBLIC KEY-----\n","extra":[]}
        if (!$ret) {
            $this->err = "获取公钥请求失败";
            return false;
        }
        $json = toJsonDecode($ret);
        if (!$json) {
            $this->err = "返回格式错误:" . $ret;
            return false;
        }

        switch (array_path($json, "code")) {
            default:
                $this->err = array_path($json, "code") ?? "返回信息错误";
                return false;
            case 0:
                $this->publicKey = array_path($json, "data.publicKey");
                break;
        }
        return true;
    }


    //获取rsa公钥
    public function getSecretIdKey(): bool
    {
        // 载入公钥
        $publicKey = openssl_pkey_get_public($this->publicKey);
        if (!$publicKey) {
            $this->err = $this->publicKey ? "公钥载入失败" : "请先getPublicKey获取公钥";
            return false;
        }
        // 生成随机32位字符串
        $randomString = bin2hex(random_bytes(16));
        // 加密随机字符串
        $result = openssl_public_encrypt($randomString, $encryptedString, $publicKey);
        if (!$result) {
            $this->err = "公钥加密失败";
            return false;
        }
        // 将加密后的字符串转换为Base64编码
        $encryptedStringBase64 = base64_encode($encryptedString);
        $ret = file_get_contents($this->url . $this->storeIdKey . "?encryptionData=" . urlencode($encryptedStringBase64));
        //{"success":true,"code":0,"codeMsg":"success","data":{"en":"VKrYa20+cB2FMkXvzkx+A5xTgYDcLsZKo\/NtKgRnZMlwZE39jAMo+3Q\/QoEZIhNvII0pkcq8zUBSg03wwZJcZAGZ7te\/Ob7\/UFqgp+je8GR0MAKQctG5vLLPESq\/kBR6"},"extra":[]}
        if (!$ret) {
            $this->err = "获取SecretIdKey请求失败";
            return false;
        }
        $json = toJsonDecode($ret);
        if (!$json) {
            $this->err = "返回格式错误:" . $ret;
            return false;
        }

        switch (array_path($json, "code")) {
            default:
                $this->err = array_path($json, "code") ?? "返回信息错误";
                return false;
            case 0:
                $en = array_path($json, "data.en");
                $deData = openssl_decrypt(base64_decode($en), 'AES-256-ECB', $randomString, OPENSSL_RAW_DATA);
                if (!$deData) {
                    $this->err = "解密失败:" . $en . "\r\nkey:" . $randomString;
                    return false;
                }
                //{"secretId":"8dc7d5906257bdd33e3f1b82e67049cd","secretKey":"48f368521bd64565e3c4dc6ad582599a"}
                $json = toJsonDecode($deData);
                $this->secretId = array_path($json, "secretId");
                $this->secretKey = array_path($json, "secretKey");
                break;
        }
        return true;
    }




    public function __call($name, $arguments)
    {
        return recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::UNDEFINED_METHOD, lang("sys.noMethodDefined"), $name, $arguments);
    }
}